package com.watchthelan.web.schedule.event;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.watchthelan.domain.Administrator;
import com.watchthelan.domain.Event;
import com.watchthelan.service.administrator.AdministratorManager;
import com.watchthelan.service.schedule.event.EventManager;
import com.watchthelan.service.server.ServerManager;

public class EventEditFormController extends SimpleFormController {
	/** Logger for this class and subclasses */
	protected final Log logger = LogFactory.getLog(getClass());
	
	private EventManager eventManager;
	private ServerManager serverManager;
	private AdministratorManager administratorManager;
	
	public ModelAndView onSubmit(Object command) throws ServletException {
		Event event = (Event) command;
		eventManager.updateEvent(event);
		return new ModelAndView(new RedirectView(getSuccessView()));
	}
	
	public Object formBackingObject(HttpServletRequest request) throws ServletException {
		logger.info("get event");
		Event event = new Event();
		String id = request.getParameter("id");
		if (id != null) {
			event = eventManager.getEventById(new Long(id));
		}
		String adminUsername = (String)request.getSession().getAttribute("administrator");
		Administrator admin = administratorManager.getAdministratorByUsername(adminUsername);
		event.setServers(serverManager.getServersOwnedBy(admin.getId()));
		// event.setForServers(eventManager.getEventsForServer(id))
		return event;
	}

	public EventManager geteventManager() {
		return eventManager;
	}

	public void seteventManager(EventManager eventManager) {
		this.eventManager = eventManager;
	}

	public ServerManager getServerManager() {
		return serverManager;
	}

	public void setServerManager(ServerManager serverManager) {
		this.serverManager = serverManager;
	}

	public AdministratorManager getAdministratorManager() {
		return administratorManager;
	}

	public void setAdministratorManager(AdministratorManager administratorManager) {
		this.administratorManager = administratorManager;
	}
	
}
